<template>
  <a-modal
    v-model:visible="visible"
    class="form-modal"
    fullscreen
    :closable="false"
    :esc-to-close="false"
    title-align="center"
    :body-style="{}"
    unmount-on-close
  >
    <template #title>
      <div style="width: 100; text-align: left">
        {{ (props.data?.id ? '编辑' : '新增') + props.title }}
      </div>
    </template>
    <div class="modal-content">
      <div>
        <div class="template-steps">
          <div class="template-steps-item">
            <a-steps
              changeable
              :current="menuKey"
              @change="changeMenu"
              line-less
            >
              <a-step><template #icon> 1 </template>基础设置</a-step>
              <a-step><template #icon> 2 </template>表单设计</a-step>
              <a-step v-if="isPreview"
                ><template #icon> 3 </template>表单预览</a-step
              >
            </a-steps>
          </div>
        </div>
      </div>
      <div class="content">
        <div class="main">
          <div class="base" v-show="menuSelected === 1">
            <div class="base-form">
              <a-form
                :model="fromData.data"
                layout="vertical"
                :rules="rules"
                ref="refForm"
              >
                <a-form-item field="name" :label="props.title + '名称'">
                  <a-input
                    size="large"
                    v-model="fromData.data.name"
                    placeholder="请输入模板名称"
                    allow-clear
                  />
                </a-form-item>
                <a-form-item
                  field="node"
                  label="组织节点"
                  v-if="isOrganizationNode"
                >
                  <a-radio-group v-model="fromData.data.node">
                    <a-radio :value="1">公司</a-radio>
                    <a-radio :value="2">部门</a-radio>
                    <a-radio :value="3">门店</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item field="enable" label="启用状态">
                  <a-switch
                    v-model="fromData.data.enable"
                    :checked-value="1"
                    :unchecked-value="2"
                  />
                </a-form-item>
                <a-form-item field="remark" label="描述">
                  <a-textarea
                    v-model="fromData.data.remark"
                    placeholder="请输入"
                    show-word-limit
                    :max-length="300"
                    :auto-size="{
                      minRows: 5
                    }"
                    allow-clear
                  />
                </a-form-item>
              </a-form>
            </div>
          </div>
          <div class="from" v-show="menuSelected === 2">
            <newSetUpForm
              ref="setUpForm"
              v-model:layout="rest"
              :businessType="props.businessType"
              @changeSeconds="changeSeconds"
              v-model:set-up-data="setUpList.data"
              :sliceName="sliceName"
            ></newSetUpForm>
          </div>
          <div class="from" v-show="menuSelected === 3">
            <!-- <PreviewForm
              v-model:layout="rest"
              :businessType="props.businessType"
              v-model:set-up-data="lookData"
            ></PreviewForm> -->
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="modal-footer">
        <a-space size="large" align="center">
          <a-button type="secondary" @click="back">取消</a-button>

          <a-button
            type="secondary"
            :disabled="+menuSelected <= 1"
            @click="onPrev"
          >
            <IconLeft />
            上一步
          </a-button>
          <a-button
            type="primary"
            v-show="isPreview ? +menuSelected !== 3 : +menuSelected !== 2"
            :disabled="+menuSelected >= 4"
            @click="onNext"
          >
            下一步
            <IconRight />
          </a-button>
          <a-button
            type="primary"
            v-show="isPreview ? +menuSelected === 3 : +menuSelected === 2"
            @click="save"
            :loading="store.isLoading"
          >
            保存
          </a-button>
        </a-space>
      </div>
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import clonedeep from 'lodash.clonedeep';
import newSetUpForm from '@/components/DynamicFormsNew/SetUpForm/index.vue';
import PreviewForm from '@/components/DynamicFormsNew/SetUpForm/PreviewForm.vue';
import { Message } from '@arco-design/web-vue';
import useGlobalParametersStore from '@/store/modules/globalParameters';
import useControlFormStore from '@/store/controlForm';
const controlFormStore = useControlFormStore();
controlFormStore.fieldNames.labelName = 'ctlCnName';
controlFormStore.fieldNames.componentType = 'ctlComponentType';

const store = useGlobalParametersStore();
const props = withDefaults(
  // 参数说明
  defineProps<{
    data?: any; // 请求table数据的函数
    add?: any; // 新增传入函数
    edit?: any; // 编辑传入函数
    validateFun?: any; // 校验函数
    fn?: any; // 刷新表格 可以自定表格ref
    businessType: string | string[]; // 总集控件编码
    title?: string;
    optionData?: any;
    isPreview?: boolean; // 是否可以预览填写表单（用于职位说明书）
    sliceName?: string; // 去除具体子集名称（例如组织基本信息，传入组织，只保留后面的基本信息）
    isOrganizationNode: boolean; // 组织节点（只有组织模板才有）
  }>(),
  {
    isPreview: false,
    isOrganizationNode: false
  }
);

let refForm = ref();
const setUpForm = ref(); // 控件ref
// 初始化
const fromData = reactive<any>({
  data: { name: '', enable: 1, remark: '' }
});

// 模板名称查重校验
const validateName = async (val: string, cb: any) => {
  try {
    if (validateData.data.edit && validateData.data.name === val) {
      return;
    } else {
      const res = await props?.validateFun(val);
      if (res.code) cb(`${res.msg}`);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 启用状态校验
const validateEnable = async (val: number, cb: any) => {
  try {
    if (fromData.data?.isShowDefault === 1 && val === 2) {
      cb('不能将默认模板的状态修改成未启用！');
      fromData.data.enable = 1;
      return;
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = {
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  node: [
    {
      required: true,
      message: '请选择'
    }
  ],
  enable: [
    {
      required: true,
      message: '请选择'
    },
    {
      validator: validateEnable
    }
  ]
};

const menuKey = ref(1);
const menuSelected = ref(1);
const visible = ref(false); // 显示弹框

// 预览数据
const lookData = computed(() => {
  if (!setUpList.data) {
    return [];
  }
  if (setUpList.data[0]?.id) {
    return setUpList.data;
  }
  if (setUpList.data) {
    // 初始化数据处理，初始化数据为三层结构
    return setUpList.data?.find((ele: any) => {
      if (
        Array.isArray(props.businessType) &&
        props.businessType.indexOf(ele.code) !== -1
      ) {
        return ele;
      } else if (ele.code === props.businessType) {
        // 二层结构数据放回
        return ele;
      }
    })?.componentList;
  }
});

// 显示全屏弹框
const fullScreen = () => {
  visible.value = true;
};
// 关闭弹窗
const back = () => {
  fromData.data = {
    name: '',
    enable: 1,
    remark: ''
  };
  visible.value = false;
  props.fn.loadData();
  menuSelected.value = 1;
  menuKey.value = 1;
  validateData.data.edit = false;
  validateData.data.name = '';
};
// 保存
const save = async (e: string) => {
  if (await refForm?.value?.validate()) {
    visible.value = true;
    return;
  } else {
    if (fromData.data.id) {
      props.edit(fromData.data, setUpList.data);
    } else {
      props.add(fromData.data, setUpList.data);
    }
    fromData.data = {
      name: '',
      enable: 1,
      remark: ''
    };
    props.fn.loadData();
    visible.value = false;
    setUpForm.value.init();
    menuSelected.value = 1;
    menuKey.value = 1;
    validateData.data.edit = false;
    validateData.data.name = '';
  }
};
// 点击标签
const changeMenu = async (e: number) => {
  if (await refForm?.value?.validate()) {
    return;
  }
  menuKey.value = e;
  menuSelected.value = e;
};

const onPrev = () => {
  menuSelected.value = Math.max(1, +menuSelected.value - 1);
  menuKey.value = menuSelected.value;
};
const onNext = async () => {
  if (await refForm?.value?.validate()) {
    menuKey.value = 1;
    return;
  } else {
    menuSelected.value = Math.min(3, +menuSelected.value + 1);
    menuKey.value = menuSelected.value;
  }

  console.log('====================================');
  console.log(menuSelected.value);
  console.log(menuKey.value);
  console.log('====================================');
  // current.value = Math.min(4, current.value + 1);
};

const validateData = reactive({
  data: { name: '', edit: false }
});
watch(
  () => props.data,
  () => {
    fromData.data = clonedeep(props.data);
    setUpList.data = clonedeep(fromData.data.seconds);
    console.log('=========== setUpList.data=========================');
    console.log(clonedeep(setUpList.data));
    console.log('====================================');
    if (props.data.id) {
      validateData.data.edit = true;
      validateData.data.name = fromData.data.name;
    }

    // 给控件新增子集code
    setUpList.data?.forEach((ele: any) => {
      ele.componentList?.forEach((item: any) => {
        item.subCode = ele.code;
      });
    });
  }
);
// 控件数据
const setUpList: any = reactive({ data: [] });
// 回传控件数据
const changeSeconds = (e: any) => {
  setUpList.data = clonedeep(e);
};

watch(
  () => setUpList.data,
  () => {
    if (Array.isArray(setUpList.data) && !setUpList.data[0]?.id) return;
    // 给控件新增子集code
    setUpList.data?.forEach((ele: any) => {
      ele.componentList?.forEach((item: any) => {
        item.subCode = ele.code;
        item.collectionId = ele.id;
      });
    });
  }
);
// 暴露方法给父组件
defineExpose({ fullScreen, save });

const rest = ref('horizontal');
</script>

<style lang="less" scoped>
.modal-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  .content {
    flex: 1;
    overflow: hidden;
  }
}

.content {
  //height: 100vh;
  // padding: 20px;
  .main {
    height: 100%;
    .base {
      background-color: #fff;
      // height: 100%;
      :deep(.arco-form-item-label-col > .arco-form-item-label) {
        font-size: 16px;
      }
      &-form {
        position: relative;
        left: 50%;
        transform: translateX(-50%);
        width: 50%;
        margin-top: 20px;
        font-weight: 700;
      }
    }

    .print-set {
      display: flex;
      height: 100%;

      .form-check {
        width: 300px;
        background: white;
        height: 100%;
        margin: 16px 0;
        overflow: auto;

        .check-item {
          display: flex;
          justify-content: space-between;
          padding: 16px;
        }
      }

      .form {
        width: 700px;
        height: 1000px;
        overflow: auto;
        margin: 20px auto;
        padding: 16px;
      }
    }
    .from {
      // border: 20px solid #f3f3f3;
      height: 100%;
    }
  }
}
:deep(.arco-modal-body) {
  flex: 1;
}
:deep(.arco-menu-item) {
  height: 100%;
  background-color: #3d7eff;
  color: #fff !important;
}
:deep(.arco-menu-selected) {
  background-color: #165dff !important;
  color: #fff;
}
:deep(.arco-menu-item:hover) {
  background-color: #165dff !important;
}
:deep(.arco-menu-selected:hover) {
  background-color: #165dff !important;
}

.modal-footer {
  text-align: center;
}
// ::v-deep .arco-modal-body {
//   padding: 0 !important;
// }
.template-steps {
  // padding: 0 160px;
  // margin-bottom: 60px;
  border: 1px solid #eee;
  min-width: 300px;
  padding: 20px;
  border-radius: 5px;
  margin: 0 auto;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  &-item {
    width: 300px;
    margin: 0 auto;
  }
}
</style>
